
import { ref } from 'vue'
import { UserForm } from '~/types/user'

export const useAuth = () => {
    const user = ref<UserForm | null>(null)

    // 初始化时从 sessionStorage 读取
    const initUser = () => {
        const userData = sessionStorage.getItem('user')
        if (userData) {
            user.value = JSON.parse(userData)
        }
    }

    initUser()

    const login = (userData: UserForm) => {
        user.value = userData
        sessionStorage.setItem('user', JSON.stringify(userData))
    }

    const logout = () => {
        user.value = null
        sessionStorage.removeItem('user')
    }

    return {
        user,
        login,
        logout
    }
}

export const { user, login, logout } = useAuth()